package com.yq.core.dao.impl;

import com.yq.core.dao.ProductDao;
import com.yq.core.dto.ProductDO;
import com.yq.core.dto.ProductDO_;
import com.yq.core.dto.UserDO;
import com.yq.core.dto.UserDO_;
import com.yq.core.po.ProductQueryPO;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yq on 16-8-28.
 */
@Stateless(name = "productDaoImpl")
public class ProductDaoImpl implements ProductDao {
    @PersistenceContext(unitName = "mallJPAUnit")
    private EntityManager entityManager;

    /**
     * 根据条件查询产品
     * */
    public List<ProductDO> queryProduct(ProductQueryPO productQueryPO) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<ProductDO> criteriaBuilderQuery = criteriaBuilder.createQuery(ProductDO.class);
        Root<ProductDO> productDORoot = criteriaBuilderQuery.from(ProductDO.class);
        List<Predicate> predicates = new ArrayList<Predicate>();
        Predicate like = criteriaBuilder.like(productDORoot.get(ProductDO_.productName), productQueryPO.getProductName());
        predicates.add(like);
        Predicate[] predicateArray = predicates.toArray(new Predicate[predicates.size()]);
        criteriaBuilderQuery.where(predicateArray);
        TypedQuery<ProductDO> productDOTypedQuery = entityManager.createQuery(criteriaBuilderQuery);
        return productDOTypedQuery.getResultList();
    }
}
